//implement GObserverTester
//andycai.sc@gmail.com 2012-04-19

#include "GObserverTester.h"
#include "GParallel/GThread.h"
#include <ctime>
#include <iostream>

using namespace std;

TimerDomain::TimerDomain(GDataReceiver* dataReceiver) : GDomainObject(dataReceiver)
{
}

TimerDomain::~TimerDomain()
{
}

void TimerDomain::schedule()
{
    time_t tTime = time(0);
    struct tm* tTm = localtime(&tTime);
    cout << "time_t = " << tTime << endl << endl;
    post(TIME_CHANGED, tTm);
}

TimerWatcher1::TimerWatcher1()
{
}

TimerWatcher1::~TimerWatcher1()
{
}

void TimerWatcher1::update(GDomainObject* domainObj)
{
    m_timerDomain = dynamic_cast<TimerDomain*>(domainObj);
}

void TimerWatcher1::process(GDomainEvent* dEvent, GDomainObject* dObject)
{
    if (dObject == m_timerDomain)
    {
        if (dEvent->getEvent() == (long)TimerDomain::TIME_CHANGED)
        {
            struct tm* tTm = (struct tm*)dEvent->getData();
            cout << "<-----------------timer watcher1---------------------->" << endl;
            cout << "<----local time:" << tTm->tm_year + 1900 << "/" << tTm->tm_mon << "/" << tTm->tm_mday
                << " " << tTm->tm_hour << ":" << tTm->tm_min << ":" << tTm->tm_sec << "------>" << endl;
            cout << "<----------------------------------------------------->" << endl << endl;
        }
    }
}

TimerWatcher2::TimerWatcher2()
{
}

TimerWatcher2::~TimerWatcher2()
{
}

void TimerWatcher2::update(GDomainObject* domainObj)
{
    m_timerDomain = dynamic_cast<TimerDomain*>(domainObj);
}

void TimerWatcher2::process(GDomainEvent* dEvent, GDomainObject* dObject)
{
    if (dObject == m_timerDomain)
    {
        if (dEvent->getEvent() == (long)TimerDomain::TIME_CHANGED)
        {
            struct tm* tTm = (struct tm*)dEvent->getData();
            cout << "<=================TIMER WATCHER2======================>" << endl;
            cout << "<=======current time:" << asctime(tTm);
            cout << "<=====================================================>" << endl << endl;
        }
    }
}

GObserverTester::GObserverTester(const string& testName) : GFrameTester(testName)
{
}

GObserverTester::~GObserverTester()
{
}

void GObserverTester::run()
{
    TimerDomain timer;
    GDomainModel<TimerDomain> timerModel;
    timer.setDataReceiver(&timerModel);

    TimerWatcher1 watcher1;
    TimerWatcher2 watcher2;

    GReceiverObserver<TimerDomain> timerObserver1(&watcher1);
    GReceiverObserver<TimerDomain> timerObserver2(&watcher2);
    timerModel.attach(&timerObserver1, TimerDomain::TIME_CHANGED);
    timerModel.attach(&timerObserver2, TimerDomain::TIME_CHANGED);

    timer.begin(1000);
    for (int i = 0; i < 20; ++i)
    {
        GThread::sleep(1000);
    }
    timer.cancel();
}

